// pages/user/xiaodian.js
//获取应用实例
const app = getApp()
var util = require('../../utils/util.js')
var http = require('../../utils/server.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showDialog: false,
    totalPrice: 0,
    selectSpecification: {},
    productList: [],
    specifications: [],
    menuData: [],
    showChooseDialog: false,
    chooseIndex: -1,
    isAdd: false,
    totalCount: 0,
    selectMenu: {
      current: -1,
      selectedCurrent: -1,
      selectedChild: [],
      selectedChildName: [],
      isShow: false,
    },
    cartList: [],
    share: 0,
    showAuthor: false,
  },
  onLoad: function(options) {
    var that = this;
    that.data.id = options.id || '';
    const scene = decodeURIComponent(options.scene)
    that.data.uid = options.uid ? options.uid : scene
    that.data.share = options.share || 0;
    //用户信息
    app.getUserInfo(function(userInfo) {
      if (userInfo != null) {
        console.info(userInfo)
      } else {
        that.setData({
          showAuthor: true
        })
      }
    })
  },
  onShow: function() {
    var that = this;
    that.setData({
      showAuthor: false
    })

    //小店信息
    http.post({
      url: "Gang/getMemberInfo",
      id: that.data.uid
    }, function(data) {
      console.log('小店详情', data);
      that.data.id = data.shop_info.id
      var tags = [];
      var shopInfo = data.shop_info;
      for (var i in shopInfo.tags) {
        var item = {};
        item.name = data.config_tags[i];
        item.good = i < 100;
        item.count = shopInfo.tags[i];
        tags.push(item);
      }
      console.info("tags", tags);
      data.tags = tags;

      that.setData({
        info: data
      })
      that.getData()
    })

    //筛选条件
    http.post({
      url: "product/getFilterData"
    }, function(data) {
      console.log('筛选条件', data)
      that.setData({
        menuData: data
      })
    })

  },

  onParentEvent: function(e) {
    app.loginServer(app.globalData.code, e.detail.encryptedData, e.detail.iv, this.getData)
  },
  getData: function(typeid = '', brandid = '') {
    var that = this
    //商品列表
    http.post({
      url: "shop/getShopProduct",
      shop_id: that.data.id,
      type: typeid,
      brand: brandid
    }, function(data) {
      console.log('商品列表', data)
      if (data != null) {
        that.setData({
          productList: data
        })
      }
    })
  },
  onShareAppMessage: function() {

  },
  menuTap: function(e) {
    var selectMenu = this.data.selectMenu;
    selectMenu.isShow = !selectMenu.isShow;
    if (selectMenu.current != e.currentTarget.dataset.index)
      selectMenu.isShow = true;
    selectMenu.current = e.currentTarget.dataset.index;
    this.setData({
      selectMenu: selectMenu
    })
  },

  childMenuTap: function(e) {
    var that = this;
    var selectMenu = this.data.selectMenu;
    selectMenu.isShow = false;
    selectMenu.selectedCurrent = e.currentTarget.dataset.pid;
    selectMenu.selectedChild[selectMenu.selectedCurrent] = e.currentTarget.dataset.index;
    selectMenu.selectedChildName[selectMenu.selectedCurrent] = e.currentTarget.dataset.name;
    this.setData({
      selectMenu: selectMenu
    })
    var typeid = selectMenu.selectedChild[0]
    var brandid = selectMenu.selectedChild[1]
    that.getData(typeid, brandid)
  },
  calcCartCount: function() {
    var total = 0;
    var cartList = this.data.cartList;
    for (var i = 0; i < cartList.length; i++) {
      total += cartList[i].count;
    }
    return total;
  },
  calcTotalPrice: function() {
    var total = 0;
    var cartList = this.data.cartList;
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].price == null) {
        continue;
      }
      total += (cartList[i].count * cartList[i].specification.gang_price);
    }
    return Math.round(total * 100) / 100;
  },
  getCartProductById: function(id, spec) {
    var cartList = this.data.cartList;
    for (var i = 0; i < cartList.length; i++) {
      if (id === cartList[i].id && spec === cartList[i].specification.title) {
        return i;
      }
    }
    return null;
  },
  getProductById: function(id) {
    var productList = this.data.productList;
    for (var i = 0; i < productList.length; i++) {
      if (id === productList[i].id) {
        return productList[i];
      }
    }
    return null;
  },
  toggleDialog: function() {
    this.setData({
      showDialog: !this.data.showDialog,
    })
  },
  toggleChooseDialog: function() {
    this.setData({
      showChooseDialog: !this.data.showChooseDialog,
    })
  },
  add: function(e) {
    this.data.chooseIndex = e.currentTarget.dataset.index;
    var specifications = this.data.productList[this.data.chooseIndex].specifications;

    this.setData({
      specifications: specifications,
      showChooseDialog: true,
    })
    this.data.isAdd = true;
  },
  sub: function(e) {
    this.data.chooseIndex = e.currentTarget.dataset.index;
    var specifications = this.data.productList[this.data.chooseIndex].specifications;

    this.setData({
      specifications: specifications,
      showChooseDialog: true,
    })
    this.data.isAdd = false;

  },
  cartSub: function(e) {
    var index = e.currentTarget.dataset.index;
    var cartItem = this.data.cartList[index];
    if (cartItem == null) {
      return;
    }

    cartItem.count = cartItem.count - 1;
    var item = this.getProductById(cartItem.id);
    if (cartItem.count <= 0) {
      this.data.cartList.splice(index, 1);
    }

    if (item != null) {
      item.num = item.num == null || item.num < 1 ? 0 : item.num - 1;
    }

    console.info(this.data.productList)
    this.data.totalPrice = this.calcTotalPrice();
    var totalCount = this.calcCartCount();
    this.setData({
      productList: this.data.productList,
      cartList: this.data.cartList,
      totalPrice: this.data.totalPrice,
      totalCount: totalCount
    });
  },
  cartAdd: function(e) {
    var index = e.currentTarget.dataset.index;
    var cartItem = this.data.cartList[index];
    if (cartItem == null) {
      return;
    }
    cartItem.count = cartItem.count + 1;
    var item = this.getProductById(cartItem.id);
    if (item != null) {
      item.num = item.num + 1;
    }
    console.info(this.data.cartList)
    this.data.totalPrice = this.calcTotalPrice();
    var totalCount = this.calcCartCount();
    this.setData({
      productList: this.data.productList,
      cartList: this.data.cartList,
      totalPrice: this.data.totalPrice,
      totalCount: totalCount
    });
  },
  clearCart: function() {
    var cartList = this.data.cartList;
    for (var i = 0; i < cartList.length; i++) {
      var item = this.getProductById(cartList[i].id);
      if (item != null) {
        item.count = 0;
      }
    }
    this.setData({
      productList: this.data.productList,
      cartList: [],
      totalPrice: 0,
      totalCount: 0
    });
  },
  copy: function(o) {
    return JSON.parse(JSON.stringify(o));
  },
  selectSpecificationTap: function(e) {
    var s = this.data.selectSpecification
    s.index = e.currentTarget.dataset.index
    s.data = this.data.specifications[s.index]
    this.setData({
      selectSpecification: s
    })
  },
  toCart: function() {
    var s = this.data.selectSpecification;
    var index = this.data.chooseIndex;
    var product = this.data.productList[index];
    var item = this.copy(product);
    item.specification = item.specifications[s.index]
    if (!item.specification)
      return util.showError('请选择规格')

    var i = this.getCartProductById(item.id, item.specification.title);
    var cartItem = this.data.cartList[i]; 
    if (cartItem == null) {
      if (!this.data.isAdd) {
        return;
      }
      cartItem = item;
      cartItem.count = 1;
      this.data.cartList.push(cartItem);
    } else {
      if (this.data.isAdd) {
        cartItem.count = cartItem.count + 1;
      } else {
        cartItem.count = cartItem.count - 1;
      }
    }

    if (this.data.isAdd) {
      product.num = product.num == null ? 1 : product.num + 1;
    } else {
      product.num = product.num - 1;
    }

    if (cartItem.count <= 0) {
      this.data.cartList.splice(i, 1);
    }
    var totalPrice = this.calcTotalPrice();
    console.info(totalPrice)
    console.info(this.data.cartList)
    var totalCount = this.calcCartCount();
    this.setData({
      productList: this.data.productList,
      cartList: this.data.cartList,
      totalPrice: totalPrice,
      totalCount: totalCount,
      showChooseDialog: false
    });
  },
  createOrder: function(e) {
    var that = this;
    var cartList = that.data.cartList;
    var len = cartList == null ? 0 : cartList.length;
    if (len == 0) {
      util.showError("请选择商品");
      return;
    }
    if (len > 1) {
      var flag = cartList[0].id
      for (i in cartList) {
        if (flag != cartList[i].id) {
          flag = false
          break
        }
      }
      if (!flag) {
        util.showModal("当前版本不支持同时购买多种商品");
        return;
      }
    }
    var productIds = [];
    var specifications = [];
    var nums = [];
    for (var i = 0; i < len; i++) {
      console.info(i, cartList[i])
      productIds.push(cartList[i].id);
      specifications.push(cartList[i].specification.title);
      nums.push(cartList[i].count);
    }
    var path = "/pages/order/ordering/ordering?shop_id=" + that.data.id + "&product_ids=" + productIds.join() + "&specifications=" + specifications.join() + "&numbers=" + nums.join();
    wx.navigateTo({
      url: path,
    })

  }
})